package com.decoration.basic.controller;

import com.alibaba.fastjson.JSONObject;
import com.decoration.basic.BasicController;

import com.decoration.basic.entity.JsonResult;
import com.decoration.basic.service.DecPictureService;
import com.decoration.basic.util.DateFormatUtils;
import com.decoration.basic.util.Global;
import com.decoration.basic.util.VerifyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/common")
public class CommonController extends BasicController {
    // 日志记录器
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    private static final String STR_BODY = "body";
    @Resource
    private DecPictureService pictureService;


    //验证码生成
    @RequestMapping(value = "/verifyCode", method = RequestMethod.GET)
    public void getVerifyCode(HttpServletRequest req, HttpServletResponse resp, HttpSession session) {
        // 设置响应的类型格式为图片格式
        resp.setContentType("image/jpeg");
        // 禁止图像缓存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        VerifyUtil vCode = new VerifyUtil(120, 40, 4, 25);
        session.setAttribute("code", vCode.getCode().toUpperCase());
        try {
            vCode.write(resp.getOutputStream());
        } catch (IOException e) {
            log.error("生成验证码异常",e);
        }
    }

    /**
     * 文件上传控制器,只能上传图片
     *
     * @param files
     * @param req
     * @param resp
     */
    @PostMapping(value = "/upload")
    @ResponseBody
    public JsonResult upload(@RequestParam(value = "files", required = false) MultipartFile[] files
                        , HttpServletRequest req,
                        HttpServletResponse resp, JsonResult jsonResult) {

        String path = Global.PICTURE_UPLOAD_DIR;
        Date date = new Date();
        String dynamicPath = DateFormatUtils.diyDateFormat("/yyyyMMdd", date);
        path += dynamicPath;
        int i = 1;
        List<String> msg = new ArrayList<String>();
        List<String> result = new ArrayList<String>();
        if (files.length > 0 && files.length < 7) {
            for (MultipartFile file : files) {
                if (file.getSize() > 40960000) {
                    jsonResult.setCode(JsonResult.FAILED_CODE);
                    jsonResult.setMsg("上传失败,文件过大,最大只能上传40M!");
                    Map<String, Object> data = new HashMap<String, Object>();
                    data.put("src", file.getName());
                    data.put("title", file.getOriginalFilename());
                    jsonResult.setData(data);
                    return jsonResult;
                } else {
                    String fileName = date.getTime() + "00" + String.valueOf(i) + ".jpg";
                    File targetFile = new File(path, fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    log.info(path);
                    //方便APP调用,设置为全地址
                    //String uploadPath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()  + req.getContextPath() + "/static/upload" + dynamicPath + "/" + fileName;
                    String uploadPath = Global.PICTURE_DOWNLOAD_URL + dynamicPath + "/" + fileName;
                    try {
                        file.transferTo(targetFile);
                    } catch (Exception e) {
                        msg.add(path + File.separator + fileName);
                        e.printStackTrace();
                        continue;
                    }
                    i++;
                    //result.put(file.getOriginalFilename(),uploadPath);
                    pictureService.add(req.getParameter("account"), uploadPath, file.getName());
                    result.add(uploadPath);
                }
            }
        }
        if (i == 1) {
            jsonResult.setCode(JsonResult.FAILED_CODE);
            jsonResult.setMsg("上传失败");
            jsonResult.setCount(msg.size());
            jsonResult.setData(msg);
            return jsonResult;
        }

        jsonResult.setCode(JsonResult.SUCCESS_CODE);
        jsonResult.setMsg("上传成功");
        jsonResult.setCount(result.size());
        jsonResult.setData(result);
        return jsonResult;
    }

    //本地测试图片上传使用
    @PostMapping(value = "/localupload")
    @ResponseBody
    public JsonResult localupload(@RequestParam(value = "files", required = false) MultipartFile[] files, HttpServletRequest req,
                                  HttpServletResponse resp, JsonResult jsonResult) {

        String path = req.getSession().getServletContext().getRealPath("static") + "/upload";
        //String path = Global.PICTURE_UPLOAD_DIR;
        Date date = new Date();
        String dynamicPath = DateFormatUtils.diyDateFormat("/yyyyMMdd", date);
        path += dynamicPath;
        int i = 1;
        List<String> msg = new ArrayList<String>();
        List<String> result = new ArrayList<String>();

        if (files.length > 0 && files.length < 7) {
            for (MultipartFile file : files) {
                if (file.getSize() > 1024000) {
                    jsonResult.setCode(JsonResult.FAILED_CODE);
                    jsonResult.setMsg("上传失败,文件过大,最大只能上传10M!");
                    Map<String, Object> data = new HashMap<String, Object>();
                    data.put("src", file.getName());
                    data.put("title", file.getOriginalFilename());
                    jsonResult.setData(data);
                    return jsonResult;
                } else {
                    String fileName = date.getTime() + "00" + String.valueOf(i) + ".jpg";
                    File targetFile = new File(path, fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    log.info(path);
                    //方便APP调用,设置为全地址
                    String uploadPath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/static/upload" + dynamicPath + "/" + fileName;
                    //String uploadPath = Global.PICTURE_DOWNLOAD_URL + dynamicPath + "/" + fileName;
                    try {
                        file.transferTo(targetFile);
                    } catch (Exception e) {
                        msg.add(path + File.separator + fileName);
                        e.printStackTrace();
                        continue;
                    }
                   /* String picId = String.valueOf(SnowFlake.getInstance().nextId());
                    DecorationPicture pic = new DecorationPicture();
                    pic.setPicInfId(picId);
                    pic.setPicAddress(uploadPath);
                    Boolean res = pictureService.add(pic);
                    if (res){
                        //log.error("插入数据库失败");
                        continue;
                    }*/
                    i++;
                    pictureService.add(req.getParameter("account"), uploadPath, file.getName());
                    //result.put(file.getOriginalFilename(),uploadPath);
                    result.add(uploadPath);
                }

            }
        }
        if (i == 1) {
            jsonResult.setCode(JsonResult.FAILED_CODE);
            jsonResult.setMsg("上传失败");
            jsonResult.setCount(msg.size());
            jsonResult.setData(msg);
            return jsonResult;
        }
        jsonResult.setCode(JsonResult.SUCCESS_CODE);
        jsonResult.setMsg("上传成功");
        jsonResult.setCount(result.size());
        jsonResult.setData(result);
        return jsonResult;
    }

    /**
     * description 获取request中的body json 数据转化为map
     *
     * @param request 1
     * @return java.util.Map<java.lang.String , java.lang.String>
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> getRequestBodyMap(ServletRequest request) {
        Map<String, String> dataMap = new HashMap<>(16);
        // 判断是否已经将 inputStream 流中的 body 数据读出放入 attribute
        if (request.getAttribute(STR_BODY) != null) {
            // 已经读出则返回attribute中的body值
            return (Map<String, String>) request.getAttribute(STR_BODY);
        } else {
            try {
                Map<String, Object> maps = JSONObject.parseObject(request.getInputStream(), Map.class);
                maps.forEach((key, value) -> dataMap.put(key, String.valueOf(value)));
                request.setAttribute(STR_BODY, dataMap);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return dataMap;
        }
    }

}

